import { LOGIN, LOGOUT, SET_USER_INFO, REFRESH_INFO } from 'Constants/userConstants';
import Cookies from 'js-cookie';

const initialState = {
  id: Cookies.get('id') || 0,
  isLogin: Cookies.get('_isLogin') === 'true',
  username: sessionStorage.getItem('username') || '',
  nickname: '',
  userId: sessionStorage.getItem('userId') || '',
  userSocketAuth: sessionStorage.getItem('userSocketAuth') || '',
  permissions: sessionStorage.getItem('permissions') ? JSON.parse(sessionStorage.getItem('permissions')).permissions : [],
};

export default function userReducer(state = initialState, action) {
  switch (action.type) {
    case LOGIN:
      Cookies.set('id', action.userInfo.id);
      Cookies.set('_isLogin', 'true');
      return Object.assign({}, state, {
        isLogin: true,
        ...action.userInfo,
      });
    case LOGOUT:
      Cookies.remove('id');
      Cookies.remove('_isLogin');
      sessionStorage.removeItem('userId');
      sessionStorage.removeItem('userSocketAuth');
      sessionStorage.removeItem('username');
      sessionStorage.removeItem('permissions');
      return Object.assign({}, initialState, {
        isLogin: false,
      });
    case SET_USER_INFO:
      Cookies.set('_isLogin', 'true');
      return Object.assign({}, state, {
        userId: action.info.userId,
        userSocketAuth: action.info.userSocketAuth,
        username: action.info.username,
        nickname: action.info.nickname,
        permissions: action.info.permissions,
        isLogin: true
      });
    case REFRESH_INFO:
      sessionStorage.setItem('permissions', JSON.stringify({ permissions: action.info.permissions }));
      return Object.assign({}, state, {
        userId: action.info.userId,
        nickname: action.info.nickname,
        permissions: action.info.permissions,
      });
    default:
      return state;
  }
}
